import Taro from '@tarojs/taro';
import { MaterialIcons } from 'taro-icons';
import React, { useState, useEffect, useMemo } from 'react';
import { View, Text, Button, Slider, Textarea } from '@tarojs/components';
import ImageLoader from '../../components/ImageLoader';
import ScoreStar from '../../components/scoreStar';
import PageHeader from '../../components/pageHeader';
import { uploadUserFile } from '../../contexts/store';
import DataErrorView from '../../components/dataError';
import EmptyContent from '../../components/emptyContent';
import UserGenderImage from '../../components/userGender';
import DataLoadingView from '../../components/dataLoading';
import { UserAvatarImage } from '../../components/userAvatar';
import { useAppContext } from '../../contexts/AppContext';

import { getMyCoachApi } from '../../api/myself';
import { updateCoachCommentReplyApi, getCoachUserCommentsApi, updateCoachCommentApi } from '../../api/coachApi';
import { assetsFileUrl } from '../../api/client';


import './index.scss';

/**
 * 用户教练页面
 * 用于展示用户的教练列表和相关信息
 */
const UserCoachPage: React.FC = () => {
  const { userInfo } = useAppContext();
  const userId = Number(userInfo?.id);
  const [coaches, setCoaches] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [currentLicenseImage, setCurrentLicenseImage] = useState('');
  const [isLicenseModalVisible, setIsLicenseModalVisible] = useState(false);
  
  // 评价相关状态
  const [isEvaluateModalVisible, setIsEvaluateModalVisible] = useState(false);
  const [selectedCoachId, setSelectedCoachId] = useState('');
  const [selectedCoachName, setSelectedCoachName] = useState('');
  const [rating, setRating] = useState<number>(5);
  const [commentContent, setCommentContent] = useState<string>('');
  const [images, setImages] = useState<{url: string, fileName: string}[]>([]);
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
  const [userComment, setUserComment] = useState<any>(null); // 用户已有的评论


  // 按状态排序教练列表: 学习中(0) > 已毕业(1) > 更换(2)
  const sortedCoaches = useMemo(() => {
    return [...coaches].sort((a, b) => a.status - b.status);
  }, [coaches]);

  /**
   * 获取教练状态样式类+
   */
  const getCoachStatusClass = (status: number) => {
    switch(status) {
      case 0: return 'user-coach-active-coach-card';
      case 1: return 'user-coach-graduated-coach-card';
      case 2: return 'user-coach-transferred-coach-card';
      default: return '';
    }
  };

  /**
   * 获取教练状态文本
   */
  const getStatusText = (status: number) => {
    switch(status) {
      case 0: return '学习中';
      case 1: return '已毕业';
      case 2: return '已更换';
      default: return '未知状态';
    }
  };

  /**
   * 加载用户教练数据
   */
  const loadCoachData = async () => {
    try {
      setLoading(true);
      setError(null);
      
      // 调用服务层API获取真实数据
      const response = await getMyCoachApi();
      
      // 检查响应状态并设置数据
      if (response && response.code === 200 && response.data) {
        setCoaches(response.data);
      } else {
        throw new Error('无效的响应数据');
      }
    } catch (err) {
      setError('加载教练数据失败，请稍后重试');
      console.error('Failed to load coach data:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadCoachData();
  }, []);

  /**
   * 刷新教练列表
   */
  const handleRefresh = () => {
    loadCoachData();
  };

  /**
   * 查看教练执照
   */
  const showLicenseModal = (imageUrl: string | undefined) => {
    setCurrentLicenseImage(imageUrl || '');
    setIsLicenseModalVisible(true);
  };

  /**
   * 关闭执照模态框
   */
  const closeLicenseModal = () => {
    setIsLicenseModalVisible(false);
  };

  /**
   * 查看教练详情
   */
  const handleViewCoachDetail = (coachId: string) => {
    Taro.navigateTo({ url: `/pages/coach-detail/index?id=${coachId}` });
  };

  /**
   * 打开评价模态框
   */
  const openEvaluateModal = async (coachId: string, coachName: string) => {
    setSelectedCoachId(coachId);
    setSelectedCoachName(coachName);

    // 获取用户已有的评论
    try {
      const response = await getCoachUserCommentsApi(Number(coachId));
      if (response.code === 200 && response.data) {
        // 查找当前用户的评论
        const currentUserComment = response.data;
        if (currentUserComment) {
          setUserComment(currentUserComment);
          setRating(currentUserComment.score || 5);
          setCommentContent(currentUserComment.content || '');
          // 转换附件格式
          const processedImages = await Promise.all(
            currentUserComment.attachments.map(async (attachment: any) => ({
              url: await assetsFileUrl(attachment.image),
              fileName: attachment.image || ''
            }))
          );
          setImages(processedImages);
        } else {
          // 没有评论则重置状态
          setUserComment(null);
          setRating(5);
          setCommentContent('');
          setImages([]);
        }
      }
    } catch (error) {
      console.error('获取评论失败:', error);
      // 失败时重置状态
      setUserComment(null);
      setRating(5);
      setCommentContent('');
      setImages([]);
    }
    
    setIsEvaluateModalVisible(true);
  };

  /**
   * 关闭评价模态框
   */
  const closeEvaluateModal = () => {
    setIsEvaluateModalVisible(false);
  };

  /**
   * 处理图片选择
   */
  const handleImagePick = () => {
    if (images.length >= 9) {
      Taro.showToast({ title: '最多上传9张图片', icon: 'none' });
      return;
    }
    
    Taro.chooseImage({
      count: 9 - images.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        try {
          const newImages: {url: string, fileName: string}[] = [];
          // 上传每张图片
          for (const tempFilePath of res.tempFilePaths) {
            try {
              let fileType = tempFilePath.split(".").pop() || 'png';
              const uploadRes:any = await uploadUserFile(tempFilePath, 'comment_image.'+fileType, 'image/png', 'comments', userId);
              if (uploadRes.code === 200 && uploadRes.data) {
                newImages.push({url: uploadRes.data.url, fileName: uploadRes.data.file_name});
              } else {
                return Taro.showToast({ title: '图片上传失败，请重试', icon: 'none' });
              }
            } catch (error) {
              console.error('上传失败:', error);
              return Taro.showToast({ title: '图片上传失败，请重试', icon: 'none' });
            }
          }
          setImages(prevImages => [...prevImages, ...newImages]);
        } catch (error) {
          console.error('图片上传失败:', error);
          Taro.showToast({ title: '图片上传失败，请重试', icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('选择图片失败:', err);
      }
    });
  };

  /**
   * 删除已选图片
   */
  const handleRemoveImage = (index: number) => {
    setImages(prevImages => prevImages.filter((_, i) => i !== index));
  };

  /**
   * 提交评价
   */
  const handleSubmitComment = async () => {
    if (!commentContent.trim()) {
      Taro.showToast({ title: '评价内容不能为空', icon: 'none' });
      return;
    }
    
    try {
      setIsSubmitting(true);
      
      // 根据是否有历史评价决定使用POST还是PUT方法
      const response = userComment ? await updateCoachCommentApi({
        coachId: Number(selectedCoachId),
        content: commentContent,
        score: rating,
        parentId: 0,
        commentId: userComment?.id || 0,
        attachments: images.map(image => ({
          id: 0,
          type: 'image',
          image: image.fileName
        }))
      }) : await updateCoachCommentReplyApi({
        coachId: Number(selectedCoachId),
        content: commentContent,
        score: rating,
        parentId: 0,
        commentId: userComment?.id || 0,
        attachments: images.map(image => ({
          id: 0,
          type: 'image',
          image: image.fileName
        }))
      });
      
      if (response.code === 200) {
        Taro.showToast({ title: userComment ? '评价更新成功' : '评价成功', icon: 'success' });
        closeEvaluateModal();
      } else {
        throw new Error(response.message || '评价失败');
      }
    } catch (error) {
      console.error('评价提交失败:', error);
      Taro.showToast({ 
        title: error instanceof Error ? error.message : '评价失败，请重试', 
        icon: 'none' 
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <View className="page-container">
      <PageHeader title="我的教练" />
      <View className="user-coach-content">
        {loading ? (
          <DataLoadingView />
        ) : error ? (
          <DataErrorView content={error} onClickFunc={handleRefresh} />
        ) : coaches.length === 0 ? (
          <EmptyContent title="暂无教练" />
        ) : (
          <View className="user-coach-cards">
            {sortedCoaches.map((coach) => (
              <View 
                key={`coach-${coach.id}-${coach.coach.id}`} 
                className={`user-coach-card ${getCoachStatusClass(coach.status)}`} 
                onClick={() => handleViewCoachDetail(coach.id)}
              >
                {/* 卡片头部 */}
                <View className="user-coach-card-header">
                  <View className="user-coach-card-header-left">
                    <Text className="user-coach-license-type">{coach.price.license}</Text>
                    <Text className="user-coach-license-name">{coach.price.name}</Text>
                  </View>
                  <View className={`user-coach-status-tag ${getCoachStatusClass(coach.status)}`}>
                    <Text className="user-coach-status-text">{getStatusText(coach.status)}</Text>
                  </View>
                </View>
                
                {/* 卡片内容 */}
                <View className="user-coach-card-body">
                  {/* 第一行：头像和基本信息 */}
                  <View className="user-coach-first-row">
                    {/* 教练头像 */}
                    <View className="user-coach-avatar-container">
                      <UserAvatarImage 
                        avatar={coach.coach.avatar}
                        user_id={Number(coach.coach.id) || 0}
                        user_name={coach.coach.username || '游客'}
                      />
                    </View>
                    
                    {/* 教练信息 */}
                    <View className="user-coach-info">
                      <View className="user-coach-name-row">
                        <Text className="user-coach-name text-lg">{coach.coach.username}</Text>
                        <UserGenderImage gender={coach.coach.gender} />
                        <View className="user-coach-age-experience">
                          <View className="purple-tag text-base">{coach.coach.age}岁</View>
                          <View className="magenta-tag text-base">教龄{coach.coach.experience_years}年</View>
                        </View>
                      </View>
                    </View>
                  </View>
                  
                  {/* 第二行：两列信息 */}
                  <View className="user-coach-second-row">
                    {/* 左侧列：籍贯和查看教练证 */}
                    <View className="user-coach-details">
                      <View className="lime-tag text-base">籍贯:{coach.coach.native}</View>
                      <View 
                        className="user-coach-certificate-btn" 
                        onClick={(e) => {
                          e.stopPropagation();
                          showLicenseModal(coach.coach.certificate);
                        }}
                      >
                        查看教练执照
                      </View>
                    </View>
                    
                    {/* 右侧列：城市和驾校信息 */}
                    <View className="user-coach-specialties">
                      <View className="city-tag">{coach.city_base.name}</View>
                      <View className="school-tag">{coach.coach.school}</View>
                    </View>
                  </View>

                {/* 评价按钮 */}
                <View className="user-coach-evaluate-btn-container">
                  <Button 
                    className="user-coach-evaluate-btn"
                    onClick={(e) => {
                      e.stopPropagation();
                      openEvaluateModal(coach.coach.id, coach.coach.username);
                    }}
                  >
                    评价
                  </Button>
                </View>

                </View>

              </View>
            ))}
          </View>
        )}
      </View>

      {/* 自定义执照图片模态框 */}
      {isLicenseModalVisible && (
          <View className="user-coach-license-modal-overlay">
          <View className="user-coach-license-modal">
            <View className="user-coach-license-modal-header">
              <Text className="user-coach-license-modal-title">教练执照信息</Text>
              <Text className="user-coach-license-modal-close" onClick={closeLicenseModal}>
                <MaterialIcons name="close" size={20} />
              </Text>
            </View>
            <View className="user-coach-license-modal-content">
              {currentLicenseImage ? (
                <ImageLoader 
                  src={currentLicenseImage} 
                  mode="aspectFit" 
                  className="user-coach-license-image"
                />) : (
                <Text className="user-coach-no-license-text">暂无执照信息</Text>
              )}
            </View>
            <View className="user-coach-license-modal-footer">
              <Button 
                  className="user-coach-license-modal-button"
                  onClick={closeLicenseModal}
                >
                关闭
              </Button>
            </View>
          </View>
        </View>
      )}

      {/* 评价模态框 */}
      {isEvaluateModalVisible && (
        <View className="user-coach-evaluate-modal-overlay">
          <View className="user-coach-evaluate-modal">
            <View className="user-coach-evaluate-modal-header">
              <Text className="user-coach-evaluate-modal-title">评价教练</Text>
              <Text className="user-coach-evaluate-modal-close" onClick={closeEvaluateModal}>
                <MaterialIcons name="close" size={20} />
              </Text>
            </View>
            
            <View className="user-coach-evaluate-modal-content">
              {/* 教练信息 */}
              <View className="user-coach-evaluate-coach-info">
                <Text className="user-coach-evaluate-coach-name">{selectedCoachName}</Text>
              </View>
              
              {/* 评分区域 */}
              <View className="user-coach-evaluate-rating-section">
                <Text className="user-coach-evaluate-rating-label">请打分：</Text>
                <ScoreStar score={rating} />
                <Slider className="user-coach-evaluate-stars text-base" 
                  step={0.1} 
                  trackSize='20'
                  onChange={(e) => setRating(e.detail.value)}
                  value={rating} 
                  showValue
                  min={0} max={5}/>
              </View>
              
              {/* 评论内容 */}
              <View className="user-coach-evaluate-comment-section">
                <Text className="user-coach-evaluate-comment-label">评价内容：</Text>
                <Textarea focus={true}
                  className="user-coach-evaluate-textarea"
                  placeholder="请输入您对教练的评价..."
                  value={commentContent}
                  autoHeight={true}
                  onInput={(e) => setCommentContent(e.detail.value)}
                  maxlength={300}
                />
                <Text className="user-coach-evaluate-comment-count">
                  {commentContent.length}/300
                </Text>
              </View>
              
              {/* 图片上传区域 */}
              <View className="user-coach-evaluate-image-section">
                <Text className="user-coach-evaluate-image-label">上传图片（最多9张）：</Text>
                <View className="user-coach-evaluate-image-grid">
                  {/* 已选图片 */}
                  {images.map((image, index) => (
                    <View key={index} className="user-coach-evaluate-image-item">
                      <ImageLoader 
                        src={image.url} 
                        mode="aspectFill" 
                        className="user-coach-evaluate-image"
                      />
                      <View 
                        className="user-coach-evaluate-image-delete"
                        onClick={() => handleRemoveImage(index)}
                      >
                        <MaterialIcons name="close" size={16} color="white" />
                      </View>
                    </View>
                  ))}
                  
                  {/* 添加图片按钮 */}
                  {images.length < 9 && (
                    <View 
                      className="user-coach-evaluate-image-add"
                      onClick={handleImagePick}
                    >
                      <MaterialIcons name="add" size={24} color="#999" />
                    </View>
                  )}
                </View>
              </View>
            </View>
            
            <View className="user-coach-evaluate-modal-footer">
              <Button 
                plain
                className="user-coach-evaluate-cancel-button"
                onClick={closeEvaluateModal}
                disabled={isSubmitting}
              >
                取消
              </Button>
              <Button 
                className="user-coach-evaluate-submit-button"
                onClick={handleSubmitComment}
                disabled={isSubmitting || !commentContent.trim()}
                loading={isSubmitting}
              >
                {isSubmitting ? '提交中...' : '提交评价'}
              </Button>
            </View>
          </View>
        </View>
      )}
    </View>
  );
};

export default UserCoachPage;